<template>
  <div class="text-fall-container">
    <div class="text-container">
      <div
        v-for="(word, index) in wordsArray"
        :key="index"
        class="word"
        ref="words"
        :style="{ backgroundColor: getRandomColor(index) }"
      >
        {{ word }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { gsap } from "gsap";

// 要展示的文本
const text = ref("Send beautiful emails that convert");
const wordsArray = computed(() => text.value.split(" "));
const words = ref([]);

// 生成随机颜色的函数
const getRandomColor = (index: number) => {
  const colors = [
    "#FFD6E0",
    "#FFEFCF",
    "#D1F0FF",
    "#C9E4DE",
    "#EDEEC9",
    "#DFD3C3",
    "#F0DBDB",
    "#D5E3F0",
    "#E0F0D5",
    "#F0E5D5",
  ];
  return colors[index];
};

onMounted(() => {
  // 检测客户端
  if (typeof window !== "undefined") {
    words.value = Array.from(document.querySelectorAll(".word"));
    // 初始状态：所有单词在视口上方且不可见
    gsap.set(words.value, {
      y: -100,
      opacity: 0,
    });

    // 创建动画：单词依次掉落
    gsap.to(words.value, {
      y: 0,
      opacity: 1,
      stagger: 0.15, // 每个单词之间的延迟
      duration: 0.8,
      ease: "bounce.out", // 弹跳效果
      onComplete: () => {
        console.log("动画完成");
      },
    });
  }
  // 获取所有单词的引用

  // 可以添加重复动画的逻辑
  // setTimeout(() => {
  //   resetAndPlayAnimation();
  // }, 5000);
});

// 重置并重新播放动画的函数
const resetAndPlayAnimation = () => {
  gsap.set(words.value, {
    y: -100,
    opacity: 0,
  });

  gsap.to(words.value, {
    y: 0,
    opacity: 1,
    stagger: 0.15,
    duration: 0.8,
    ease: "bounce.out",
  });
};
</script>

<style lang="scss" scoped>
.text-fall-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  width: 100%;
  overflow: hidden;
  background-color: #f5f5f5;
}

.text-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  max-width: 80%;
  gap: 10px;
}

.word {
  display: inline-block;
  font-size: 1.8rem;
  font-weight: bold;
  color: #0c41b2;
  padding: 8px 12px;
  border-radius: 6px;
  margin: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
